# -*- coding: utf-8 -*-
"""
Created on Thu Apr  1 16:00:29 2021

@author: Apple
"""

import os
import sys
from PyQt5.QtWidgets import (QAbstractItemView,QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem,QHeaderView)
from main_window import Ui_MainWindow
from PyQt5.QtCore import Qt
import pandas as pd
import numpy as np

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        tableWidget1 = self.ui.tableWidget1
        tableWidget1.setRowCount(1)
        tableWidget1.setColumnCount(2)
        tableWidget1 = self.ui.tableWidget1
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,0,newItem)
        self.ui.actionopenfile.triggered.connect(self.openfile)
        self.ui.actionversion.triggered.connect(self.showversion)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,1,newItem)
        global A
        A = ['x','f(x)']
        tableWidget1.setHorizontalHeaderLabels(A)
        
        tableWidget2 = self.ui.tableWidget2
        tableWidget2.setRowCount(1)
        tableWidget2.setColumnCount(1)
        tableWidget2 = self.ui.tableWidget2
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,0,newItem)
        global B
        B = ['x']
        tableWidget2.setHorizontalHeaderLabels(B)
        
        global numx
        global numn
        numx = 0
        numn = 0

    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版号为 V1.0 ')

    def newtable(self):
        global numx
        data = self.ui.lineEditnumX.text()
        if data.isdigit():
            print('it is an integer')
        else:
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个大于1的整数')
            return
        data = int(data)
        numx = data
        tableWidget1 = self.ui.tableWidget1
        tableWidget1.setRowCount(data)
        
        for i in range(data):
            for j in range(2):                
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,j,newItem)           
    
    def newrow(self):
        global numx
        tableWidget1 = self.ui.tableWidget1
        numrow = tableWidget1.rowCount()
        numcol = tableWidget1.columnCount()
        tableWidget1.insertRow(numrow)
        for i in range(numcol):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget1.setItem(numrow,i,newItem)
        numx = numrow+1
        self.ui.lineEditnumX.setText(str(numrow+1))
    
    def delrow(self):
        global numx
        tableWidget1 = self.ui.tableWidget1
        numrow = tableWidget1.rowCount()
        numcol = tableWidget1.columnCount()
        if numrow == 1:
            tableWidget1.removeRow(0)
            tableWidget1.insertRow(0)
            for i in range(numcol):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(0,i,newItem)            
        else:
            tableWidget1.removeRow(numrow-1)
        numx = numrow-1
        self.ui.lineEditnumX.setText(str(numrow-1))
    
    def diftable(self):
        global numx
        tableWidget1 = self.ui.tableWidget1
        tableWidget1.setRowCount(numx)
        tableWidget1.setColumnCount(numx+1) 
        for i in range(1,numx):
            A.append(f'{i}阶差商')
        tableWidget1.setHorizontalHeaderLabels(A)
        
        x = []
        f = []
        data = pd.read_csv('1.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        for i in range(numx):
            x.append(Data[i][0])
            f.append(Data[i][1])
        
        
        rows=numx        #行数
        cols=numx+1      #列数
        temp=[[0 for col in range(cols)] for row in range(rows)]
        for i in range(rows):
            temp[i][0]=x[i]
            temp[i][1]=f[i]
     
        for i in range(1,rows):
            for j in range(2,i+2):
                temp[i][j]=(temp[i][j-1]-temp[i-1][j-1])/(temp[i][0]-temp[i-j+1][0])
                newItem = QTableWidgetItem(f'{format(temp[i][j],".6f")}')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,j,newItem)
        tableWidget1.setEditTriggers(QAbstractItemView.NoEditTriggers)
        path = os.getcwd() + '\\2.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = temp)
        test.to_csv(path,index=0)

    
    def savedata(self):
        tableWidget1 = self.ui.tableWidget1
        numrow = tableWidget1.rowCount()
        numcol = tableWidget1.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget1.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        path = os.getcwd() + '\\1.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')
                
        
    def cleartable(self):
        global A
        A = ['x','f(x)']
        self.ui.tableWidget1.clear()
        self.ui.lineEditnumX.clear()
        self.ui.tableWidget1.setRowCount(1)
        self.ui.tableWidget1.setColumnCount(2)
        tableWidget1 = self.ui.tableWidget1
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,1,newItem)
        tableWidget1.setHorizontalHeaderLabels(A)
        tableWidget1.setEditTriggers(QAbstractItemView.AllEditTriggers)
    
    def settable(self):
        global numn
        data = self.ui.lineEditnumN.text()
        if data.isdigit():
            print('it is an integer')
        else:
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个大于1的整数')
            return
        data = int(data)
        numn = data
        tableWidget2 = self.ui.tableWidget2
        tableWidget2.setRowCount(data)
        
        for i in range(data):
            for j in range(2):                
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,j,newItem)
        B = ['x','N(x)']
        tableWidget2.setHorizontalHeaderLabels(B)
        
    def newrowN(self):
        global numx
        tableWidget2 = self.ui.tableWidget2
        numrow = tableWidget2.rowCount()
        numcol = tableWidget2.columnCount()
        tableWidget2.insertRow(numrow)
        for i in range(numcol):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget2.setItem(numrow,i,newItem)
        numx = numrow+1
        self.ui.lineEditnumN.setText(str(numrow+1))
    
    def delrowN(self):
        global numx
        tableWidget2 = self.ui.tableWidget2
        numrow = tableWidget2.rowCount()
        numcol = tableWidget2.columnCount()
        if numrow == 1:
            tableWidget2.removeRow(0)
            tableWidget2.insertRow(0)
            for i in range(numcol):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(0,i,newItem)            
        else:
            tableWidget2.removeRow(numrow-1)
        numx = numrow-1
        self.ui.lineEditnumN.setText(str(numrow-1)) 

    def cleartableN(self):
        global B
        B = ['x']
        tableWidget2 = self.ui.tableWidget2
        tableWidget2.clear()
        self.ui.lineEditnumN.clear()
        tableWidget2.setRowCount(1)
        tableWidget2.setColumnCount(1)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,0,newItem)
        tableWidget2.setHorizontalHeaderLabels(B)          
        tableWidget2.setEditTriggers(QAbstractItemView.AllEditTriggers)
        
    def savedataN(self):
        tableWidget2 = self.ui.tableWidget2
        numrow = tableWidget2.rowCount()
        numcol = tableWidget2.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget2.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        path = os.getcwd() + '\\3.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')
    
    def transNtoC(self,methodname):
        methodCode = 0
        if methodname == '线性插值':
            methodCode = 1
        elif methodname == '抛物插值':
            methodCode  = 2
        elif methodname =='三次插值':
            methodCode  = 3
   
        return methodCode  
    
    def CalNvalue(self):
        global numn
        global numx
        tableWidget2 = self.ui.tableWidget2
        tableWidget2.setRowCount(numn)
        tableWidget2.setColumnCount(2) 
        B = ['x','近似值']
        tableWidget2.setHorizontalHeaderLabels(B)
        
        data1 = pd.read_csv('2.csv')
        data2 = pd.read_csv('3.csv')
        Data1 = data1.iloc[:,:].values.tolist()
        Data2 = data2.iloc[:,:].values.tolist()
        
        methodname = self.ui.comboBox.currentText()
        methodCode = self.transNtoC(methodname)
        
        if methodCode == 1:
            for i in range(numn):
                value = Data1[0][1]+(Data2[i][0]-Data1[0][0])*Data1[1][2]
                newItem = QTableWidgetItem(f'{format(value,".6f")}')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,1,newItem)
                
        if methodCode == 2:
            for i in range(numn):
                value = Data1[0][1]+(Data2[i][0]-Data1[0][0])*Data1[1][2]+(Data2[i][0]-Data1[0][0])*(Data2[i][0]-Data1[1][0])*Data1[2][3]
                newItem = QTableWidgetItem(f'{format(value,".6f")}')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,1,newItem)            
                   
        if methodCode == 3:
            for i in range(numn):
                value = Data1[0][1]+(Data2[i][0]-Data1[0][0])*Data1[1][2]+(Data2[i][0]-Data1[0][0])*(Data2[i][0]-Data1[1][0])*Data1[2][3]+(Data2[i][0]-Data1[0][0])*(Data2[i][0]-Data1[1][0])*(Data2[i][0]-Data1[2][0])*Data1[3][4]
                newItem = QTableWidgetItem(f'{format(value,".6f")}')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,1,newItem)            

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())